package c11;

import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 线程池也要指定名称
 * 线程默认名称来源于ThreadFactory,可参考DefaultThreadFactory
 */
public class TestThreadPool {
    private static ThreadPoolExecutor executorOne=
            new ThreadPoolExecutor(5,5,1,TimeUnit.MILLISECONDS,new LinkedBlockingQueue<>(),
                    new NamedThreadFactory("ASYN-ACCEPT-POOL"));
    private static ThreadPoolExecutor executorTwo=
            new ThreadPoolExecutor(5,5,1,TimeUnit.MILLISECONDS,new LinkedBlockingQueue<>(),
                    new NamedThreadFactory("ASYN-PROCESS-POOL"));
    public static void main(String[] args){
        //接受用户链接模块
        executorOne.execute(new Runnable() {
            @Override
            public void run() {
                System.out.println("接受用户链接线程");
                throw new NullPointerException();
            }
        });

        //业务处理模块
        executorTwo.execute(new Runnable() {
            @Override
            public void run() {
                System.out.println("具体业务请求处理线程");
            }
        });

        executorOne.shutdown();
        executorTwo.shutdown();
    }

    public static class NamedThreadFactory implements ThreadFactory{

        private static final AtomicInteger poolNumber = new AtomicInteger(1);
        private final ThreadGroup group;
        private final AtomicInteger threadNumber = new AtomicInteger(1);
        private final String namePrefix;

        NamedThreadFactory(String name) {
            SecurityManager s = System.getSecurityManager();
            group = (s != null) ? s.getThreadGroup() :
                    Thread.currentThread().getThreadGroup();
            if(null==name||name.isEmpty()){
                name="pool";
            }
            namePrefix = name+"-" +
                    poolNumber.getAndIncrement() +
                    "-thread-";
        }

        public Thread newThread(Runnable r) {
            Thread t = new Thread(group, r,
                    namePrefix + threadNumber.getAndIncrement(),
                    0);
            if (t.isDaemon())
                t.setDaemon(false);
            if (t.getPriority() != Thread.NORM_PRIORITY)
                t.setPriority(Thread.NORM_PRIORITY);
            return t;
        }
    }
}
